package com.starblink.imgsearch.result.ui

import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.RectF
import android.graphics.drawable.Drawable
import android.media.MediaPlayer
import android.os.Build
import android.os.Bundle
import android.util.Size
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.view.postDelayed
import androidx.core.view.updateLayoutParams
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.viewpager.widget.ViewPager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.FragmentUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.Priority
import com.bumptech.glide.load.DecodeFormat
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.*
import com.bumptech.glide.request.target.Target
import com.bumptech.glide.request.transition.Transition
import com.starblink.android.basic.adapter.MutableAdapter
import com.starblink.android.basic.base.activity.BaseTVMActivity
import com.starblink.android.basic.config.GuangConfig
import com.starblink.android.basic.ext.*
import com.starblink.android.basic.extension.apollo.toWrap
import com.starblink.android.basic.extension.dp2px
import com.starblink.android.basic.extension.extraOf
import com.starblink.android.basic.extension.lazyOnNone
import com.starblink.android.basic.extension.navigationTo
import com.starblink.android.basic.sensorsdata.room.entity.SkAntEntity
import com.starblink.android.basic.sensorsdata.spm.GTrackerAssistUtils
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmElementDef
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.sensorsdata.spm.event.TrackEvent
import com.starblink.android.basic.sensorsdata.spm.impl.SpmTrackHandler
import com.starblink.android.basic.util.FlowCountDownTimer
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.android.common.view.decoration.SpaceItemDecoration
import com.starblink.basic.ext.*
import com.starblink.basic.log.SKLogger
import com.starblink.basic.route.RoutePage
import com.starblink.basic.storage.SkStorage
import com.starblink.basic.style.bottomsheet.PagerBottomSheetBehavior
import com.starblink.basic.style.view.mutian.AnimationResourceModel
import com.starblink.basic.style.view.recyclerview.SimpleGapItemDecor
import com.starblink.basic.util.ActivityStackManage
import com.starblink.basic.util.CommUtils
import com.starblink.basic.util.log.YYLogUtils
import com.starblink.imgsearch.R
import com.starblink.imgsearch.databinding.ActivityImgSearchResultBinding
import com.starblink.imgsearch.databinding.ItemSearchBrandBinding
import com.starblink.imgsearch.ext.defaultBoxRect
import com.starblink.imgsearch.result.data.ImgClipModel
import com.starblink.imgsearch.result.data.ResultBrandModel
import com.starblink.imgsearch.result.data.ResultPriceModel
import com.starblink.imgsearch.result.ext.box2RectF
import com.starblink.imgsearch.result.ext.rect2BoxStr
import com.starblink.imgsearch.result.ui.cell.BrandChildCell
import com.starblink.imgsearch.result.ui.cell.ImgClipTabVH
import com.starblink.imgsearch.result.ui.fragment.ImgSearchingFragment
import com.starblink.imgsearch.result.ui.widget.SearchHintAdapter
import com.starblink.imgsearch.result.ui.widget.ThingsPagerAdapter
import com.starblink.rocketreserver.fragment.PicSearchResultF
import com.starblink.rocketreserver.fragment.SearchWordVOF
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import razerdp.blur.BlurHelper

/**
 * 图搜结果页
 */
@Route(path = RoutePage.ImageSearch.PAGE_RESULT)
class ImgSearchResultTVMActivity :
    BaseTVMActivity<ActivityImgSearchResultBinding, ResultVM>(), ViewPager.OnPageChangeListener {

    override fun isStatusBarLightMode(): Boolean = false

    override fun initViewBinding(): ActivityImgSearchResultBinding =
        ActivityImgSearchResultBinding.inflate(layoutInflater)

    @Autowired(name = RoutePage.ImageSearch.ARGS_FILE_PATH)
    @JvmField
    var filePath: String = ""

    @Autowired(name = RoutePage.ImageSearch.ARGS_IMG_URL)
    @JvmField
    var imgUrl: String = ""

    @Autowired(name = RoutePage.ImageSearch.ARG_POST_PIC_ID)
    @JvmField
    var postPicId: String = ""


    private val fireworksModels =
        arrayListOf(
            AnimationResourceModel(
                "img_search_result_anim",
                "anim_fireworks_",
                "frame",
                false,
                50
            )
        )

    private val btSheetCallback by lazyOnNone<PagerBottomSheetBehavior.BottomSheetCallback> {
        object : PagerBottomSheetBehavior.BottomSheetCallback() {
            override fun onStateChanged(bottomSheet: View, newState: Int) {
                fragments.forEachIndexed { _, similarTabFragment ->
                    similarTabFragment.bottomSheetExpand =
                        newState == PagerBottomSheetBehavior.STATE_EXPANDED
                }
            }

            override fun onSlide(bottomSheet: View, slideOffset: Float) {
//                Log.d(TAG, "onSlide : $slideOffset")
                viewBinding.vBgMask.alpha = slideOffset * 0.85f
                viewBinding.imgDim.alpha = slideOffset * 0.85f
            }

        }
    }

    private var bottomSheetBehavior: PagerBottomSheetBehavior<View>? = null

    private var imgSize: Size? = null

    private var imgBmp: Bitmap? = null

    private val clipImgAdapter by lazyOnNone {
        MutableAdapter(viewModel.imgClipData).apply {
            addVhDelegate {
                ImgClipTabVH(it) { position ->
                    viewBinding.viewPager.setCurrentItem(position, true)
                    refreshTopBrand(position)
                    initSearchAction(position)
                }
            }
        }
    }

    //单个主体的tab
    private val brandAdapter: MutableAdapter by lazyOnNone {
        MutableAdapter(viewModel.brandList).apply {
            //类目
            addVhDelegate {
                BrandChildCell(
                    proxyClick = { position ->
                        clickBrandData(position)
                    },
                    ItemSearchBrandBinding.inflate(it.inflater, it, false)
                )
            }
        }
    }

    private var mp: MediaPlayer? = null

    private var pagerAdapter: ThingsPagerAdapter? = null

    private var fragments = arrayListOf<ResultTabFragment>()
    override fun onDestroy() {
        mp?.release()
        super.onDestroy()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
//        BarUtils.transparentNavBar(this)
        super.onCreate(savedInstanceState)
    }

    override fun initData() {
        super.initData()
        viewModel.filePath = filePath
        viewModel.imgUrl = imgUrl
        viewModel.postPicId = postPicId
        viewModel.loadData()
        SKLogger.i(TAG, "filePath: $filePath")
        SKLogger.i(TAG, "imgUrl: $imgUrl")
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.navigationBarColor = Color.parseColor("#000000")
        }

        //等待fragment刷新后刷新顶部tab
        FlowBus.with<Int>(FlowConst.IMG_SEARCH_SWITCH_PAGE).register(this) { position ->
            refreshTopBrand(position)
        }

        //圈选区域没有获取到数据 走AI推荐
        FlowBus.with<Int>(FlowConst.IMG_SEARCH_OOPS).register(this) { position ->
            refreshTopBrandNoData(position)
        }
        //获取底纹词完成后 刷新底纹词数据
        FlowBus.with<Int>(FlowConst.IMG_SEARCH_KEY_WORD).register(this) { pageIndex ->
            initSearchAction(pageIndex)
        }
    }

    //点击顶部brand按钮
    private fun clickBrandData(brandIndex: Int) {
        val pageIndex = viewBinding.viewPager.currentItem
        try {
            viewModel.brandMapList[pageIndex]?.let {
                if (brandIndex == 0) {//点击all
                    if (it[0].selected) {
                        return
                    } else {
                        it[0].selected = true
                        for ((i, item) in it.withIndex()) {
                            if (i != 0) {
                                item.selected = false
                            }
                        }
                    }
                } else {//点击其他
                    it[brandIndex].selected =
                        !it[brandIndex].selected
                    var allStatus = true
                    it.forEach { md ->
                        allStatus = !md.selected && allStatus
                    }
                    it[0].selected = allStatus
                }
            }
        } catch (e: Exception) {
            YYLogUtils.e("数组越界~~")
        } finally {
            refreshTopBrand(pageIndex)
            MainScope().launch {
                FlowBus.with<Int>(FlowConst.IMG_SEARCH_BRAND_ITEM_CLICK).post(pageIndex)
            }
        }
    }

    private fun refreshTopBrand(pageIndex: Int) {
        try {
            viewModel.brandList.clear()
            viewModel.brandMapList[pageIndex].let { brandList ->
                if (!brandList.isNullOrEmpty()) {
                    viewModel.brandList.addAll(brandList)
                }
            }
            viewModel.priceMapList[pageIndex]?.let {
                if (it.currentCountryIsolateFlag == true) {
                    viewBinding.priceLay.visible()
                    when (it.status) {
                        //从低到高 升序
                        1 -> {
                            viewBinding.icPol1.setImageResource(R.drawable.ic_polygon_1_choice)
                            viewBinding.icPol2.setImageResource(R.drawable.ic_polygon_2)
                        }
                        //从高到低 降序
                        2 -> {
                            viewBinding.icPol1.setImageResource(R.drawable.ic_polygon_1)
                            viewBinding.icPol2.setImageResource(R.drawable.ic_polygon_2_choice)
                        }

                        else -> {
                            viewBinding.icPol1.setImageResource(R.drawable.ic_polygon_1)
                            viewBinding.icPol2.setImageResource(R.drawable.ic_polygon_2)
                        }
                    }

                } else {
                    viewBinding.priceLay.gone()
                }
            }
        } catch (e: Exception) {
            YYLogUtils.e("数组越界~~")
        } finally {
            brandAdapter.notifyDataSetChanged()
        }
    }

    private fun refreshTopBrandNoData(pageIndex: Int) {
        viewModel.brandList.clear()
        viewModel.brandMapList[pageIndex] = arrayListOf()
        brandAdapter.notifyDataSetChanged()
    }

    var firstScore = 0.0
    override fun initView() {
        super.initView()
        loadImg()
        showSearching()

        viewBinding.btnBack.setOnClickListener {
            finish()
        }
        viewModel.dataLD.observe(this) {
            onViewSuccess()
        }
        viewBinding.actionPanel.imgClips.viewTreeObserver.addOnGlobalLayoutListener {
            viewBinding.actionPanel.vClipsShadow.visibleOrGone(viewBinding.actionPanel.imgClips.childCount >= 3)
        }

        viewBinding.brandRv.enableCorner(16.dp2px())

        viewBinding.priceLay.setOnClickListener {
            val currentItem = viewBinding.viewPager.currentItem
            viewModel.priceMapList[currentItem]?.let {
                it.status = it.status + 1
                if (it.status > 2) {
                    it.status = 0
                }
                //埋点
                SpmTrackHandler.addSingleTrackData(
                    SkAntEntity(
                        spmCnt = GTrackerAssistUtils.fetchElementValue(
                            SpmPageDef.GdsAndPostItemTab,
                            SpmElementDef.StoreListFeaturedClick
                        ),
                        params = when (it.status) {
                            1 -> {
                                mapOf("sortord" to "asc")
                            }

                            2 -> {
                                mapOf("sortord" to "desc")
                            }

                            else -> {
                                mapOf()
                            }
                        }
                    )
                )

                refreshTopBrand(currentItem)
                MainScope().launch {
                    FlowBus.with<Int>(FlowConst.IMG_SEARCH_BRAND_ITEM_CLICK).post(currentItem)
                }
            }
        }

    }

    private fun loadImg() {
        val url = imgUrl.ifEmpty { filePath }
        viewBinding.img.adjustViewBounds = true
        viewBinding.imgDim.adjustViewBounds = true
        Glide.with(this).asBitmap().apply(RequestOptions().apply {
            format(DecodeFormat.PREFER_ARGB_8888)
        }).override(Target.SIZE_ORIGINAL).load(url)
            .skipMemoryCache(false)
            .priority(Priority.IMMEDIATE)
            .into(object : CustomViewTarget<ImageView, Bitmap>(viewBinding.img) {
                override fun onLoadFailed(errorDrawable: Drawable?) {

                }

                override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                    imgBmp = resource //Bitmap.createBitmap(resource)
                    viewBinding.root.post {
                        viewBinding.img.updateLayoutParams {
                            val cRadio =
                                viewBinding.vMeasure.width.toFloat() / viewBinding.vMeasure.measuredHeight
                            imgSize = Size(resource.width, resource.height)
                            if (imgSize!!.width.toFloat() / imgSize!!.height >= cRadio) {
                                width = viewBinding.vMeasure.width
                                height = ViewGroup.LayoutParams.WRAP_CONTENT
                            } else {
                                height = viewBinding.vMeasure.height
                                width = ViewGroup.LayoutParams.WRAP_CONTENT
                            }

                            viewBinding.imgDim.layoutParams?.width = width
                            viewBinding.imgDim.layoutParams?.height = height
                        }
                        viewBinding.img.setImageBitmap(imgBmp)
                        viewBinding.img.enableCorner(32.dp)
                        viewBinding.img.post {
                            initThingsAndView()
                        }
                        lifecycleScope.launch(Dispatchers.Default) {
                            try {
                                val blurBmp = BlurHelper.blur(
                                    this@ImgSearchResultTVMActivity,
                                    Bitmap.createBitmap(imgBmp!!), // 创建新对象，内部调用会recycle
                                    viewBinding.img.width,
                                    viewBinding.img.height,
                                    10f,
                                )
                                lifecycleScope.launch {
                                    viewBinding.imgDim.setImageBitmap(blurBmp)
                                }
                            } catch (ex: Exception) {
                                ex.printStackTrace()
                            }
                        }
                    }
                }

                override fun onResourceCleared(placeholder: Drawable?) {

                }

            })
    }

    private fun onViewSuccess() {
        val timeTag = nowTime()
        viewBinding.resultLayout.visible()
        hideSearching()
        viewBinding.resultLayout.updateLayoutParams<ViewGroup.MarginLayoutParams> {
            topMargin = 44.dp2px()
//            bottomMargin = CommUtils.getBottomStatusHeight()
        }
        viewBinding.resContentLayout.updateLayoutParams<CoordinatorLayout.LayoutParams> {
            bottomSheetBehavior = (this.behavior as? PagerBottomSheetBehavior<View>)?.also {
                it.addBottomSheetCallback(btSheetCallback)
            }
        }

        val data = viewModel.dataLD.value
        firstScore = data?.list?.firstOrNull()?.productF?.score ?: 0.0
        playSuccessSound()
        //处理1.2新增的品牌筛选
        setBrandUI(data)

        pagerAdapter = ThingsPagerAdapter(supportFragmentManager, fragments)
        if (viewModel.boxesList.isEmpty()) {
            viewBinding.brandRvLay.gone()
            viewBinding.viewPager.enableCorner(32.dp2px(), "top")
            //走AI逻辑
            viewModel.priceMapList[0] = ResultPriceModel(0, data?.currentCountryIsolateFlag)
            fragments.add(
                ResultTabFragment.newInstance(
                    0,
                    picUrl = viewModel.imgUrl,
                    region = "",
                    postPicAiId = if (viewModel.postAIList.isNotEmpty()) viewModel.postAIList[0].id else null,
                    list = data?.list?.mapIndexedNotNull { i, p -> p?.productF?.toWrap(i) },
                    selectOtherCountryFlag = data?.selectOtherCountryFlag,
                    currentCountryIsolateFlag = data?.currentCountryIsolateFlag,
                    mTopTotalNum = data?.total ?: 0,
                    brandMapList = viewModel.brandMapList,
                    priceMapList = viewModel.priceMapList,
                    searchWordMapList = viewModel.searchWordMapList
                )
            )
        } else {
            viewBinding.brandRvLay.visible()
            viewBinding.viewPager.enableCorner(0, "top")
            //得到坐标点
            viewModel.boxesList.forEachIndexed { index, s ->
                viewModel.priceMapList[index] =
                    ResultPriceModel(0, if (index == 0) data?.currentCountryIsolateFlag else null)
                fragments.add(ResultTabFragment.newInstance(
                    index,
                    picUrl = viewModel.imgUrl,
                    region = s ?: "",
                    postPicAiId = if (index < viewModel.postAIList.size) viewModel.postAIList[index].id else null,
                    list = if (s == viewModel.curBox) data?.list?.mapIndexedNotNull { i, p ->
                        p?.productF?.toWrap(
                            i
                        )
                    } else null,
                    selectOtherCountryFlag = data?.selectOtherCountryFlag,
                    currentCountryIsolateFlag = data?.currentCountryIsolateFlag,
                    mTopTotalNum = data?.total ?: 0,
                    brandMapList = viewModel.brandMapList,
                    priceMapList = viewModel.priceMapList,
                    searchWordMapList = viewModel.searchWordMapList
                ))
            }
        }
        viewBinding.viewPager.bindFragment(
            pagerAdapter = pagerAdapter!!,
            pageChangeListener = this
        )


        bottomSheetBehavior?.also {
            it.peekHeight =
                if (viewBinding.img.measuredHeight > 0) {
                    val result = if (viewBinding.img.measuredHeight > appScreenHeight * 0.8) {
                        (appScreenHeight * 0.2).toInt()
                    } else {
                        (appScreenHeight - viewBinding.root.paddingTop - viewBinding.img.measuredHeight - 20.dp2px())
                    }
                    result
                } else (appScreenHeight * 0.2).toInt()
            it.halfExpandedRatio = 0.6F
        }

        viewBinding.imgLay.post {
            viewBinding.imgLay.gravity = Gravity.TOP
            viewBinding.img.enableCorner(0.dp)
        }
        initThingsAndView()
        initSearchAction(0)
        anim2Top(1200L)
        viewBinding.vBgMask.visible()
        viewBinding.imgDim.visible()
        refreshTopBrand(0)
        SKLogger.d(TAG, "onViewSuccess spent: ${nowTime() - timeTag} ms")
    }


    @SuppressLint("NotifyDataSetChanged")
    private fun setBrandUI(data: PicSearchResultF?) {
        //顶部品牌筛选第一次组装数据
        viewModel.brandList.clear()
        var list = arrayListOf<ResultBrandModel>()
        list.add(ResultBrandModel(true, "All", "-1"))
        //默认All时给一个点击
        SpmTrackHandler.addSingleTrackData(
            SkAntEntity(
                spmCnt = GTrackerAssistUtils.fetchElementValue(
                    SpmPageDef.GdsAndPostItemTab,
                    SpmElementDef.Element_33049
                ),
            )
        )
        if (data?.filterBrandList?.isNotEmpty() == true) {
            for ((i, item) in data.filterBrandList!!.withIndex()) {
                if (i < 5) {//取前5
                    item?.brandVOF?.name?.let {
                        list.add(ResultBrandModel(false, it, item.brandVOF.id ?: ""))
                    }
                }
            }
        }
        viewModel.brandMapList[0] = list
        list.forEach {
            viewModel.brandList.add(ResultBrandModel(it.selected, it.brandTxt, it.brandId))
        }
        viewBinding.brandRv.let {
            if (it.adapter == null) {
                var subManager = LinearLayoutManager(ActivityStackManage.currentActivity())
                subManager.orientation = LinearLayoutManager.HORIZONTAL
                it.layoutManager = subManager
                it.setHasFixedSize(true)
                it.itemAnimator = null
                it.addItemDecoration(
                    SpaceItemDecoration.newHorizontalDecoration(CommUtils.dip2px(8))
                )
                it.adapter = brandAdapter
            } else {
                it.scrollToPosition(0)
                brandAdapter.notifyDataSetChanged()
            }
        }
    }

    private fun anim2Top(delay: Long) {
        viewBinding.root.postDelayed(delay) {
            bottomSheetBehavior?.state = PagerBottomSheetBehavior.STATE_EXPANDED
            //给个动画
            if (firstScore >= 0.7 || SkStorage.getBoolean(GuangConfig.ANIM_KEY, false)) {
                viewBinding.animFireworks.visible()
                viewBinding.animFireworks.setFrameAnim(fireworksModels)
                viewBinding.animFireworks.postDelayed(2000L) {
                    viewBinding.animFireworks.gone()
                }
            } else {
                viewBinding.animFireworks.gone()
            }
        }
    }

    private fun initThingsAndView() {
        imgBmp ?: return
        imgSize ?: return
        if (!viewModel.dataLoaded) {
            return
        }

        // 为空时，本地补充一个空的
        val curRect = viewModel.curBox?.box2RectF() ?: imgSize!!.defaultBoxRect()
        viewModel.boxesList.map { it.box2RectF() }.let {
            viewModel.rectBoxes.addAll(it)
        }
        viewModel.rectBoxes.takeIf { it.isEmpty() }?.add(curRect)

        viewBinding.imgThings.trackPage = SpmPageDef.ImgSearch2Route
        viewBinding.imgThings.apply {
            updateLayoutParams<FrameLayout.LayoutParams> {
                this.width = viewBinding.img.measuredWidth
                this.height = viewBinding.img.measuredHeight
            }
            imgSize = this@ImgSearchResultTVMActivity.imgSize
            curRectF = curRect
            tingsRectF = viewModel.rectBoxes
            onDraggedPosition = {
                onDragged(it)
            }
            onHotPotClick = { position, rect ->
                viewBinding.viewPager.setCurrentItem(position, true)
                refreshTopBrand(position)
                initSearchAction(position)
            }
        }

        val curPosition = viewModel.rectBoxes.indexOfFirst { curRect == it }
        viewBinding.actionPanel.imgClips.layoutManager =
            LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
        viewBinding.actionPanel.imgClips.addItemDecoration(SimpleGapItemDecor(8.dp2px()))
        viewModel.imgClipData.clear()
        viewModel.rectBoxes.forEachIndexed { index, it ->
            viewModel.imgClipData.add(
                ImgClipModel(
                    imgBmp = imgBmp!!.createBitmap(
                        it.left.toInt(),
                        it.top.toInt(),
                        it.width().toInt(),
                        it.height().toInt()
                    ),
                    selected = curPosition == index,
                ),
            )
        }
        viewBinding.actionPanel.imgClips.adapter = clipImgAdapter
        clipImgAdapter.refreshAll()

    }


    override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {

    }

    override fun onPageSelected(position: Int) {
        viewModel.rectBoxes.takeIf { it.isNotEmpty() && position < it.size }?.run {
            viewBinding.imgThings.curRectF = get(position)
        }
        viewModel.imgClipData.forEachIndexed { index, imgClipModel ->
            imgClipModel.selected = index == position
        }
        clipImgAdapter.refreshAll()
    }

    override fun onPageScrollStateChanged(state: Int) {

    }

    private fun playSuccessSound() {
        mp = MediaPlayer().apply {
            val assetsFD = assets.openFd("voice/search_success.mp3")
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                setDataSource(assetsFD)
            } else {
                setDataSource(assetsFD.parcelFileDescriptor.fileDescriptor)
            }
            prepareAsync()
            setOnPreparedListener {
                it.start()
            }
            setOnCompletionListener {
                release()
            }
            setOnErrorListener { mp, what, extra ->
                mp.release()
                true
            }
        }
    }

    private fun onDragged(rect: RectF) {
        pagerAdapter ?: return
        SpmTrackHandler.addSingleTrackData(
            SkAntEntity(
                event = TrackEvent.elementClick.value,
                spmCnt = GTrackerAssistUtils.fetchElementValue(
                    SpmPageDef.ImgSearch2Route,
                    SpmElementDef.GuideScanImgResultDragAndAdjust
                ),
                params = mapOf()
            )
        )

        rect.scale(imgSize!!.width / viewBinding.imgThings.measuredWidth.toFloat())

        if (viewModel.rectBoxes.size >= MAX_TAB_SIZE || viewModel.isLastBoxFromDrag) {
            fragments.last().apply {
                picUrl = viewModel.imgUrl
                region = rect.rect2BoxStr()
                reload()
            }
            viewModel.rectBoxes.last().set(rect)
            viewModel.imgClipData.last().apply {
                imgBmp = this@ImgSearchResultTVMActivity.imgBmp!!.createBitmap(
                    rect.left.toInt(),
                    rect.top.toInt(),
                    rect.width().toInt(),
                    rect.height().toInt()
                )
                selected = true
            }
            clipImgAdapter.notifyItemChanged(viewModel.imgClipData.lastIndex)
        } else {
            viewModel.priceMapList[fragments.size] = ResultPriceModel(0, null)
            fragments.add(
                ResultTabFragment.newInstance(
                    fragments.size,
                    picUrl = viewModel.imgUrl,
                    region = rect.rect2BoxStr(),
                    list = null,
                    selectOtherCountryFlag = null,
                    brandMapList = viewModel.brandMapList,
                    priceMapList = viewModel.priceMapList,
                    searchWordMapList = viewModel.searchWordMapList
                )
            )
            viewModel.imgClipData.add(
                ImgClipModel(
                    imgBmp = this@ImgSearchResultTVMActivity.imgBmp!!.createBitmap(
                        rect.left.toInt(),
                        rect.top.toInt(),
                        rect.width().toInt(),
                        rect.height().toInt()
                    ),
                    selected = true,
                ),
            )
            viewModel.rectBoxes.add(rect)
            pagerAdapter?.notifyDataSetChanged()
            viewModel.isLastBoxFromDrag = true
        }
        viewBinding.viewPager.offscreenPageLimit = pagerAdapter!!.count - 1
        viewBinding.viewPager.setCurrentItem(pagerAdapter!!.count - 1, true)
        viewBinding.actionPanel.imgClips.scrollToPosition(viewModel.imgClipData.size - 1)

        anim2Top(200L)
    }

    private fun showSearching() {
        viewBinding.loadingLayout.visible()
        FragmentUtils.add(
            supportFragmentManager,
            ImgSearchingFragment.newInstance(),
            viewBinding.loadingLayout.id,
            ::ImgSearchingFragment.name,
            false,
            true
        )
    }

    private fun hideSearching() {
        supportFragmentManager.popBackStackImmediate()
        viewBinding.loadingLayout.gone()
    }

    var words = arrayListOf<String>()
    var wordsBean = arrayListOf<SearchWordVOF>()

    val wordAdapter = SearchHintAdapter(words)
    private fun initSearchAction(tabIndex: Int) {
        if (tabIndex != viewBinding.viewPager.currentItem) return
        val emptyHintStr = string(R.string.search_hint_img)
//        val words = viewModel.dataLD.value?.searchWordList?.mapNotNull { it?.searchWordVOF }
        words.clear()
        wordsBean.clear()
        if (viewModel.searchWordMapList.size == 0) {
            words.add(emptyHintStr)
            wordsBean.add(SearchWordVOF(showWord = emptyHintStr, null, null))
        } else if (viewModel.searchWordMapList.size > tabIndex) {
            val ww = viewModel.searchWordMapList[tabIndex]
            if (ww.isNullOrEmpty()) {
                words.add(emptyHintStr)
                wordsBean.add(SearchWordVOF(showWord = emptyHintStr, null, null))

//                words.add("11111-$tabIndex")
//                wordsBean.add(SearchWordVOF(showWord ="11111-$tabIndex","11111",null))
            } else {
                ww.forEach {
                    it?.searchWordVOF?.showWord?.let { str ->
                        words.add(str)
                        wordsBean.add(it.searchWordVOF)
                    }
                }
            }
        }

        val isPanelBinding = viewBinding.actionPanel
        if (isPanelBinding.flipper.adapter != null) {
            wordAdapter.notifyDataSetChanged()
        } else {
            isPanelBinding.flipper.adapter = wordAdapter
            isPanelBinding.vBgSearch.setOnClickListener {

                var searchTerm: String? = null

                navigationTo(url = RoutePage.Search.PAGE_SEARCH) {
                    extraOf(
                        RoutePage.Search.ARG_SHADING_WORD to isPanelBinding.flipper.run {
                            var curShading: SearchWordVOF? = null

                            if (wordsBean.isNullOrEmpty()) {
                                curShading = null
                            }
                            if (words.isNotEmpty()) {
                                curShading = wordsBean[displayedChild]
                            }
                            if (curShading?.showWord == emptyHintStr) {
                                curShading = null
                            }
                            searchTerm = curShading?.showWord
                            curShading
                        },
                        RoutePage.Search.ARG_HISTORY_TAG to "img",
                    )
                }

                if (searchTerm == null) {
                    SpmTrackHandler.addSingleTrackData(
                        SkAntEntity(
                            spmCnt = GTrackerAssistUtils.fetchElementValue(
                                SpmPageDef.GdsAndPostItemTab, SpmElementDef.HomeNewSearchBar_33002
                            ),
                        )
                    )
                } else {
                    SpmTrackHandler.addSingleTrackData(
                        SkAntEntity(
                            spmCnt = GTrackerAssistUtils.fetchElementValue(
                                SpmPageDef.GdsAndPostItemTab, SpmElementDef.HomeNewSearchBar_33002
                            ),
                            params = mapOf("searchTerm" to searchTerm!!)
                        )
                    )
                }
            }
            isPanelBinding.btnSearch.setOnClickListener {

                val model = isPanelBinding.flipper.run {
                    var curShading: SearchWordVOF? = null
                    if (words.isNotEmpty()) {
                        curShading = wordsBean[displayedChild]
                    }
                    if (curShading?.showWord == emptyHintStr) {
                        curShading = null
                    }
                    curShading
                }
                val url = model?.linkUrl
                if (url?.isNotEmpty() == true) {
                    navigationTo(url = url)
                } else {
                    navigationTo(url = RoutePage.Search.PAGE_SEARCH) {
                        extraOf(
                            RoutePage.Search.ARG_KEY_WORD to (model?.actualWord?.ifEmpty { model.showWord }),
                            RoutePage.Search.ARG_HISTORY_TAG to "img",
                        )
                    }
                }

                if (model?.actualWord == null) {
                    SpmTrackHandler.addSingleTrackData(
                        SkAntEntity(
                            spmCnt = GTrackerAssistUtils.fetchElementValue(
                                SpmPageDef.GdsAndPostItemTab, SpmElementDef.Element_33003
                            ),
                        )
                    )
                } else {
                    SpmTrackHandler.addSingleTrackData(
                        SkAntEntity(
                            spmCnt = GTrackerAssistUtils.fetchElementValue(
                                SpmPageDef.GdsAndPostItemTab, SpmElementDef.Element_33003
                            ),
                            params = mapOf("searchTerm" to model.showWord)
                        )
                    )
                }

            }
        }
    }


    companion object {
        const val TAG = "ImgSearchActivity"
        const val MAX_TAB_SIZE = 6
    }

//    private fun mockData1() {
//        viewModel.brandList.add(ResultBrandModel(true, "11", "22"))
//        viewModel.brandList.add(ResultBrandModel(false, "212", "22"))
//        viewModel.brandList.add(ResultBrandModel(false, "323", "22"))
//        viewModel.brandList.add(ResultBrandModel(false, "4434", "22"))
//        viewModel.brandList.add(ResultBrandModel(false, "545", "22"))
//        viewModel.brandList.add(ResultBrandModel(false, "5425", "22"))
//        viewModel.brandList.add(ResultBrandModel(false, "5345", "22"))
//        viewModel.brandList.add(ResultBrandModel(false, "543335", "22"))
//        viewModel.brandList.add(ResultBrandModel(false, "5445", "22"))
//        viewModel.brandList.add(ResultBrandModel(false, "54333335", "22"))
//    }
//
//    private fun mockData2() {
//        viewModel.brandList.add(ResultBrandModel(true, "11", "22"))
//        viewModel.brandList.add(ResultBrandModel(false, "662", "22"))
//        viewModel.brandList.add(ResultBrandModel(false, "663", "22"))
//        viewModel.brandList.add(ResultBrandModel(false, "6634", "22"))
//        viewModel.brandList.add(ResultBrandModel(false, "665", "22"))
//        viewModel.brandList.add(ResultBrandModel(false, "6625", "22"))
//        viewModel.brandList.add(ResultBrandModel(false, "6645", "22"))
//        viewModel.brandList.add(ResultBrandModel(false, "663335", "22"))
//        viewModel.brandList.add(ResultBrandModel(false, "6645", "22"))
//        viewModel.brandList.add(ResultBrandModel(false, "66333335", "22"))
//    }

}